package com.maimang.platform.common.utils.encryption;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author jintaozhao@qq.com
 * @Date 2017/9/14 14:35
 * @project common-common
 * @Package com.maimang.platform.common.utils
 * @Description
 * @Modified By
 */
public class MD5Encrypt {
	// 全局数组
	private final static String[] strDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

	private static String byteToHexString(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}

	/**
	 * @author zjt
	 * @date 2017/9/14
	 * @description 转换字节数组为16进制字符串
	 */
	public static String byteArrayToHexString(byte[] bytes) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			sBuffer.append(byteToHexString(bytes[i]));
		}
		return sBuffer.toString();
	}

	public static String MD5Encode(String strObj) {
		String resultString = null;
		try {
			resultString = strObj;
			MessageDigest md = MessageDigest.getInstance("MD5");
			// md.digest() 该函数返回值为存放哈希值结果的byte数组
			resultString = byteArrayToHexString(md.digest(strObj.getBytes()));
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return resultString;
	}

}
